#include "csvdecoder.h"
#include "pointdata.h"
#include <qDebug>

CsvDecoder::CsvDecoder(void)
{
	m_line_buffer.clear();
	m_pattern = new QRegExp("(\\(.*,.*\\))");
	m_pattern->setMinimal(true);
}

CsvDecoder::~CsvDecoder()
{
}

void CsvDecoder::procLine(QByteArray line)
{
	QString strLine = QString::fromLatin1(line);

	int pos = 0;
	while(pos < strLine.length())
	{
		pos = strLine.indexOf(*m_pattern, pos);
		if (pos >= 0)
		{
			procElem(m_pattern->cap(0));
			pos += m_pattern->cap(0).length();
		}
		else
		{
			break;
		}
	}
}

void CsvDecoder::procElem(QString elem)
{
	QString elem_exclude_delm = elem.mid(1,elem.length()-2);
	QStringList list = elem_exclude_delm.split(',');
	if (2 == list.length())
	{
		emit recv_a_point(PointData(list.at(0), list.at(1)));
	}
}

void CsvDecoder::on_recv_data(QByteArray data)
{
	qDebug() << "csv decoder recv: " << data;
	for (auto c:data)
	{
		m_line_buffer.append(c);
		if ('\n' == c)
		{
			procLine(m_line_buffer);
			m_line_buffer.clear();
		}
	}
}